package com.wookii.friedeggs

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.OnResultListener
import com.baidu.ocr.sdk.exception.OCRError
import com.baidu.ocr.sdk.model.GeneralBasicParams
import com.baidu.ocr.sdk.model.GeneralResult
import com.baidu.ocr.sdk.model.WordSimple
import com.luck.picture.lib.entity.LocalMedia
import com.wookii.friedeggs.data.ClassDao
import com.wookii.friedeggs.data.Exam
import com.wookii.friedeggs.data.ExamDao
import com.wookii.friedeggs.data.Student
import com.wookii.friedeggs.data.StudentDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File


/**
 *@Author Nick.wu
 *Date 2023/9/25
 */
class MainViewModel(private val studentDao: StudentDao, private val examDao: ExamDao,  private val classDao: ClassDao) :
    ViewModel() {

    private lateinit var studentMutableList: MutableList<Student>
    private lateinit var currentExam: Exam

    private val _examFlow = MutableSharedFlow<Exam>()
    public val examFlow = _examFlow.asSharedFlow()

    //当前考试Id
    private var currentExamId: Long? = null
    private val _students = MutableLiveData<MutableList<WordSimple>>()
    val students: LiveData<MutableList<WordSimple>> = _students

    private val _showClassDialog = MutableLiveData<Boolean>()
    val showClassDialog: LiveData<Boolean> = _showClassDialog


    /**
     * 未完成的考试信息
     */
    fun getUnFinishExam() = examDao.getStudentsByExam(false)
    fun getAllExam() = examDao.getAll().asLiveData()
    fun getStudentsByPic(context: Context, localMedia: ArrayList<LocalMedia>?) {
        localMedia?.get(0)?.realPath?.let { path ->
            val param = GeneralBasicParams()
            param.setDetectDirection(true)
            param.imageFile = File(path)

            OCR.getInstance(context)
                .recognizeAccurateBasic(param, object : OnResultListener<GeneralResult> {
                    override fun onResult(result: GeneralResult?) {

                        CoroutineScope(Dispatchers.IO).launch {
                            currentExam = Exam(null, create = System.currentTimeMillis())
                            currentExamId = examDao.insert(currentExam!!)
                            studentMutableList = mutableListOf<Student>()
                            (result?.wordList as MutableList<WordSimple>?)?.forEach {
                                studentMutableList.add(
                                    Student(
                                        null,
                                        name = it.words,
                                        examId = currentExamId
                                    )
                                )
                            }
                            studentDao.insertAll(studentMutableList)
                            withContext(Dispatchers.Main) {
                                _showClassDialog.value = true
                            }
                        }
                    }

                    override fun onError(e: OCRError?) {
                        Log.e("OCR", e?.message.toString())
                    }
                })
        }
    }

    /**
     * 更新考试相关信息
     */
    fun updateExamClassName(text: CharSequence) {
        val className = text.toString()
        val classInfo: com.wookii.friedeggs.data.Class = com.wookii.friedeggs.data.Class(null, className)
        CoroutineScope(Dispatchers.IO).launch {
            //插入一个班级信息
            classDao.insert(classInfo)
            //更新student表，为每个学生添加班级信息
            studentMutableList.forEach {
                it.classInfo = classInfo
                studentDao.updateStudent(it)
            }
            //更新exam表，为考试表添加班级信息
            currentExam.classInfo = classInfo
            examDao.updateExam(currentExam)
            //这里使用了ShardFlow，非粘性
            withContext(Dispatchers.Main){
                _examFlow.emit(currentExam)
            }
        }
    }
}

class MainViewModelFactory(
    private val dao: StudentDao,
    private val examDao: ExamDao,
    private val classDao: ClassDao,

    ) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return MainViewModel(dao, examDao, classDao) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}